// NRS疼痛评估逻辑处理
import { nrsConfig } from './nrsConfig.js';

/**
 * 计算NRS疼痛评估结果
 * @param {Object} formData - 表单数据
 * @returns {Object} 评估结果
 */
export function calculateNRSAssessment(formData) {
  const result = {
    // 各项疼痛评分
    currentPain: formData.currentPain || 0,
    worstPain24h: formData.worstPain24h || 0,
    leastPain24h: formData.leastPain24h || 0,
    averagePain24h: formData.averagePain24h || 0,
    restPain: formData.restPain || 0,
    activityPain: formData.activityPain || 0,
    functionalImpact: formData.functionalImpact || 0,
    
    // 疼痛描述信息
    painLocation: formData.painLocation || '',
    painCharacter: formData.painCharacter || [],
    painDuration: formData.painDuration || '',
    painTriggers: formData.painTriggers || '',
    painRelief: formData.painRelief || '',
    
    // 计算最高疼痛评分（用于确定疼痛等级）
    maxPainScore: 0,
    
    // 疼痛等级和建议
    painLevel: '',
    painLevelColor: '',
    painLevelRange: '',
    description: '',
    recommendations: []
  };

  // 计算最高疼痛评分
  const painScores = [
    result.currentPain,
    result.worstPain24h,
    result.averagePain24h,
    result.restPain,
    result.activityPain
  ];
  result.maxPainScore = Math.max(...painScores);

  // 根据最高疼痛评分确定疼痛等级
  if (result.maxPainScore === 0) {
    const level = nrsConfig.painLevels.none;
    result.painLevel = level.name;
    result.painLevelColor = level.color;
    result.painLevelRange = level.range;
    result.description = level.description;
    result.recommendations = [...level.recommendations];
  } else if (result.maxPainScore >= 1 && result.maxPainScore <= 3) {
    const level = nrsConfig.painLevels.mild;
    result.painLevel = level.name;
    result.painLevelColor = level.color;
    result.painLevelRange = level.range;
    result.description = level.description;
    result.recommendations = [...level.recommendations];
  } else if (result.maxPainScore >= 4 && result.maxPainScore <= 6) {
    const level = nrsConfig.painLevels.moderate;
    result.painLevel = level.name;
    result.painLevelColor = level.color;
    result.painLevelRange = level.range;
    result.description = level.description;
    result.recommendations = [...level.recommendations];
  } else if (result.maxPainScore >= 7 && result.maxPainScore <= 10) {
    const level = nrsConfig.painLevels.severe;
    result.painLevel = level.name;
    result.painLevelColor = level.color;
    result.painLevelRange = level.range;
    result.description = level.description;
    result.recommendations = [...level.recommendations];
  }

  // 根据功能影响评分添加额外建议
  if (result.functionalImpact >= 7) {
    result.recommendations.push('疼痛严重影响日常功能，建议寻求专业康复治疗');
  } else if (result.functionalImpact >= 4) {
    result.recommendations.push('疼痛对日常功能有明显影响，建议调整活动方式');
  }

  // 根据疼痛性质添加建议
  if (result.painCharacter.includes('burning')) {
    result.recommendations.push('烧灼痛可能提示神经性疼痛，建议神经科评估');
  }
  if (result.painCharacter.includes('shooting')) {
    result.recommendations.push('放射痛建议进行影像学检查，排除神经压迫');
  }
  if (result.painCharacter.includes('throbbing')) {
    result.recommendations.push('搏动性疼痛建议注意血管因素，必要时心血管评估');
  }

  // 根据疼痛持续时间添加建议
  if (result.painDuration === 'chronic') {
    result.recommendations.push('慢性疼痛建议制定长期疼痛管理计划');
  } else if (result.painDuration === 'acute' && result.maxPainScore >= 7) {
    result.recommendations.push('急性重度疼痛需要及时医疗干预');
  }

  return result;
}

/**
 * 生成NRS评估报告
 * @param {Object} formData - 表单数据
 * @param {Object} result - 评估结果
 * @param {Object} recorderInfo - 记录人信息
 * @returns {string} 评估报告文本
 */
export function generateNRSReport(formData, result, recorderInfo) {
  const reportDate = new Date().toLocaleString('zh-CN');
  
  let report = `NRS疼痛评估报告\n`;
  report += `==========================================\n\n`;
  
  // 基本信息
  report += `【基本信息】\n`;
  report += `患者姓名：${formData.patientName}\n`;
  report += `年龄：${formData.age}岁\n`;
  report += `性别：${formData.gender === 'male' ? '男' : '女'}\n`;
  if (formData.diagnosis) {
    report += `诊断：${formData.diagnosis}\n`;
  }
  report += `评估时间：${formData.recordTime}\n`;
  report += `记录人：${recorderInfo.name}（${recorderInfo.position}）\n`;
  if (recorderInfo.institution) {
    report += `机构：${recorderInfo.institution}\n`;
  }
  report += `\n`;
  
  // 疼痛评分
  report += `【疼痛评分】\n`;
  report += `当前疼痛：${result.currentPain}/10\n`;
  report += `24小时最严重疼痛：${result.worstPain24h}/10\n`;
  report += `24小时最轻微疼痛：${result.leastPain24h}/10\n`;
  report += `24小时平均疼痛：${result.averagePain24h}/10\n`;
  report += `静息时疼痛：${result.restPain}/10\n`;
  report += `活动时疼痛：${result.activityPain}/10\n`;
  report += `功能影响评分：${result.functionalImpact}/10\n`;
  report += `\n`;
  
  // 疼痛等级
  report += `【疼痛等级】\n`;
  report += `等级：${result.painLevel}（${result.painLevelRange}）\n`;
  report += `描述：${result.description}\n`;
  report += `\n`;
  
  // 疼痛特征
  if (result.painLocation || result.painCharacter.length > 0 || result.painDuration) {
    report += `【疼痛特征】\n`;
    if (result.painLocation) {
      report += `疼痛部位：${result.painLocation}\n`;
    }
    if (result.painCharacter.length > 0) {
      const characterLabels = {
        'sharp': '尖锐痛/刺痛',
        'dull': '钝痛/隐痛',
        'burning': '烧灼痛',
        'throbbing': '跳痛/搏动性痛',
        'cramping': '痉挛痛',
        'aching': '酸痛',
        'shooting': '放射痛',
        'tingling': '麻刺感'
      };
      const characters = result.painCharacter.map(char => characterLabels[char] || char).join('、');
      report += `疼痛性质：${characters}\n`;
    }
    if (result.painDuration) {
      const durationLabels = {
        'acute': '急性（＜1周）',
        'subacute': '亚急性（1-4周）',
        'chronic': '慢性（＞4周）'
      };
      report += `疼痛持续时间：${durationLabels[result.painDuration]}\n`;
    }
    report += `\n`;
  }
  
  // 诱发和缓解因素
  if (result.painTriggers || result.painRelief) {
    report += `【疼痛相关因素】\n`;
    if (result.painTriggers) {
      report += `诱发因素：${result.painTriggers}\n`;
    }
    if (result.painRelief) {
      report += `缓解因素：${result.painRelief}\n`;
    }
    report += `\n`;
  }
  
  // 建议措施
  if (result.recommendations.length > 0) {
    report += `【建议措施】\n`;
    result.recommendations.forEach((rec, index) => {
      report += `${index + 1}. ${rec}\n`;
    });
    report += `\n`;
  }
  
  // 备注
  if (formData.remarks) {
    report += `【备注】\n`;
    report += `${formData.remarks}\n`;
    report += `\n`;
  }
  
  report += `==========================================\n`;
  report += `报告生成时间：${reportDate}\n`;
  
  return report;
}

/**
 * 验证NRS评估表单数据
 * @param {Object} formData - 表单数据
 * @returns {Object} 验证结果 {isValid: boolean, errors: string[]}
 */
export function validateNRSForm(formData) {
  const errors = [];
  
  // 个人信息字段已改为选填，不再进行必填验证
  // 只验证如果填写了年龄，则必须在有效范围内
  if (formData.age !== null && formData.age !== undefined && formData.age !== '') {
    const age = parseInt(formData.age);
    if (isNaN(age) || age < 0 || age > 150) {
      errors.push('年龄应在0-150岁之间');
    }
  }
  
  // 检查必填的疼痛评分
  const requiredPainFields = [
    { field: 'currentPain', name: '当前疼痛程度' },
    { field: 'worstPain24h', name: '过去24小时最严重疼痛' },
    { field: 'leastPain24h', name: '过去24小时最轻微疼痛' },
    { field: 'averagePain24h', name: '过去24小时平均疼痛' },
    { field: 'restPain', name: '静息时疼痛程度' },
    { field: 'activityPain', name: '活动时疼痛程度' },
    { field: 'functionalImpact', name: '功能影响评估' }
  ];
  
  requiredPainFields.forEach(({ field, name }) => {
    const value = formData[field];
    if (value === null || value === undefined || value === '') {
      errors.push(`请评估${name}`);
    } else if (value < 0 || value > 10) {
      errors.push(`${name}评分应在0-10之间`);
    }
  });
  
  return {
    isValid: errors.length === 0,
    errors
  };
}